<script setup>
import { TreeSelect } from 'ant-design-vue'
import { computed, onMounted, ref } from 'vue'

import useDict from '../../hooks/useDict'
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  dictTree: String,
  api: Function,
  treeDefaultExpandAll: {
    type: Boolean,
    default: true
  },

  placeholder: {
    type: String,
    default: '请选择'
  },
  showSearch: {
    type: Boolean,
    default: true
  },
  lastStage: Boolean,
  treeNodeFilterProp: {
    type: String,
    default: 'title'
  },
  display: Boolean
})
const apiOptions = ref([])
const dictStore = useDict()
function treeFunc(treeData, opts = {}) {
  return treeData.map((t) => {
    t = { ...t }
    if (t.children && t.children.length > 0) {
      if (opts.lastStage) {
        t.selectable = false
      }
      t.children = treeFunc(t.children, opts)
    } else {
      // t.selectable = true;
    }
    return t
  })
}
onMounted(async () => {
  if (props.api) {
    apiOptions.value = await props.api()
  }
  if (props.dictTree == 'org') {
    dictStore.getOrgTree()
  }
})
const myOptions = computed(() => {
  if (props.dictTree == 'org') {
    return dictStore.orgTree
  }
  let treeData = props.api ? apiOptions.value : props.data
  return treeFunc(treeData, { lastage: props.lastStage })
})
const value = defineModel('value')
const emit = defineEmits(['changeObj'])
function onChange(v, v2) {
  emit('changeObj', { value: v, title: v2[0] })
}
const text = computed(() => {
  function getItem(tree, value) {
    for (let i = 0; i < tree.length; i++) {
      if (tree[i].value == value) {
        return tree[i]
      }

      if (tree[i].children && tree[i].children.length > 0) {
        return getItem(tree[i].children, value)
      }
    }
  }

  return getItem(myOptions.value, value.value)?.title
})
</script>
<template>
  <div v-if="display">{{ text }}</div>
  <TreeSelect
    v-else
    :multiple="!!$attrs?.isMutiple"
    v-model:value="value"
    :placeholder="placeholder"
    :treeData="myOptions"
    :treeDefaultExpandAll="treeDefaultExpandAll"
    :treeNodeFilterProp="treeNodeFilterProp"
    :showSearch="showSearch"
    allowClear
    :popupClassName="$style.popup"
    @change="onChange"
  >
  </TreeSelect>
</template>
<style module lang="scss">
.popup {
  :global {
    .ant-tree-select-dropdown .ant-select-tree .ant-select-tree-treenode {
      width: 100%;
    }
  }
}
</style>
